package cn.melonlib.cores.commons.comp.web.utils;

import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class RequestUtils extends ApplicationObjectSupport implements HandlerInterceptor {

    private ThreadLocal<JsonMap<Object>> postBodys=new ThreadLocal<>();

    @Resource
    private ObjectMapper jsonMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println(request.getInputStream());
        try(InputStream in = request.getInputStream()){
            postBodys.set(JsonMap.createMap(jsonMapper.readValue(StreamUtils.copyToString(in, StandardCharsets.UTF_8), new TypeReference<Map<String,Object>>() {
            })));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        postBodys.remove();
    }

    public JsonMap<Object> getBody(){
        return postBodys.get();
    }
}
